package org.lida.converter.config;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.Charset;
import java.util.List;

/**
 * author: lida
 * create time: 2020-09-01 11:47
 * description:
 */
@SpringBootConfiguration
public class AppConfigTwo extends WebMvcConfigurationSupport {

    /**
     * 方法二：这个方法就可以给定一个消息转换器
     * 注意：有顺序，先添加 fastJsonHttpMessageConverter
     * 再添加 stringHttpMessageConverter，不然字符串传至前端会乱码
     */
    @Override
    protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName("ISO-8859-1"));
        fastJsonHttpMessageConverter.setDefaultCharset(Charset.forName("UTF-8"));
        converters.add(fastJsonHttpMessageConverter);
        converters.add(stringHttpMessageConverter);
    }

    /**
     * 添加一个拦截器
     */
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptor() {
            //执行controller之前拦截
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                System.out.println("拦截之前");
                return true;
            }

            //这个是执行完成之后 拦截
            @Override
            public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
                System.out.println("执行完成之后");
            }

            //最后执行的，如果出现了异常可以在这里进行捕获
            @Override
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
                System.out.println("最后执行");
                if (ex != null) {   //有异常
                    //搞你的东西了.....
                }
            }
        });
    }
}
